<?php

namespace app\admin\controller;

use app\models\{Agent as Agents, Product, Region, Order, OrderProduct, User as Users, Taocans};
use think\Db;
use think\Validate;
use app\facade\Redis;


class Orders extends Base
{


    public function order_excel1()
    {
        $ids = input('ids');
        $title = [
            ['field' => 'bianma', 'width' => 22, 'title' => '收货人编码'],
            ['field' => 'name', 'width' => 20, 'title' => '收货人'],
            ['field' => 'areas', 'width' => 13, 'title' => '收货区域'],
            ['field' => 'taocanid', 'width' => 13, 'title' => '套餐编码'],
            ['field' => 'taocanname', 'width' => 26, 'title' => '套餐名称'],
            ['field' => 'goods_id', 'width' => 13, 'title' => '商品编码'],
            ['field' => 'title', 'width' => 26, 'title' => '商品名称'],
            ['field' => 'guige', 'width' => 32, 'title' => '规格型号'],
            ['field' => 'unit', 'width' => 13, 'title' => '计量单位'],
            ['field' => 'number', 'width' => 13, 'title' => '数量'],
            ['field' => 'dealer', 'width' => 13, 'title' => '经销商'],
            ['field' => 'price', 'width' => 13, 'title' => '单价'],
            ['field' => 'total', 'width' => 13, 'title' => '金额'],
            ['field' => 'created', 'width' => 26, 'title' => '下单时间'],
            ['field' => 'address', 'width' => 50, 'title' => '收货区域'],
            ['field' => 'info', 'width' => 13, 'title' => '备注'],
            ['field' => 'ordersn', 'width' => 30, 'title' => '订单号'],
        ];
        //样式  示例：字段 time_difference 大于 0 的行，字体颜色为FF0000
        $conditions =  [];
        //纵向合并单元格  示例：已group_sn字段分组，值相同的合并，include_field（选择字段合并），exclude_field（排除字段合并）,可选择多个
        $merge_cells  = [
            'field' => 'ordersn', //已该字段为分组，值相同的合并
            'include_field' => [], //合并选择字段
            'exclude_field' => ['areas', 'bianma', 'guige', 'price', 'total', 'created', 'dealer', 'name', 'goods_id', 'title', 'spec', 'unit', 'number', 'address', 'info'], //合并排除字段
        ];
        $data = [];
        $ids = explode(',', $ids);
        $order = (new Order())->where(['id' => $ids])->select();
        foreach ($order as $row) {
            $products = (new OrderProduct())->where('ordersn', $row['ordersn'])->select();
            $street = getdrees($row['street'], 1);
            $status_text = $row->status_text;
            foreach ($products as $product) {
                $dealer = (new Product())->where('id', $product['productid'])->value('dealer');
                $parame = $product['parame'] ?? '';
                $parame = json_decode($parame, true) ?? [];
                $par_text = '';
                $unit = '';
                $guige = '';
                foreach ($parame as $par) {
                    if (strpos($par['name'], '单位') !== false) {
                        $unit = $par['numbers'];
                    }
                    if (strpos($par['name'], '规格') !== false) {
                        $guige = $par['numbers'];
                    }
                    $par_text = $par_text . '' . $par['name'] . ':' . $par['numbers'] . '  ';
                }
                $user = (new Users())->where('id', $row['user_id'])->find();
                $bianma = (new Agents())->where('id', ($user['agentid'] ?? 0))->value('nickname');
                $bianma = $bianma . $user['store_name'];
                $taocanid = '';
                $taocanname = '';
                if (!empty($row['taocanid'])) {
                    $taocanid = $row['taocanid'];
                    $taocanname = (new Taocans())->where('id', $taocanid)->value('titles') ?? '';
                }
                $data[] = [
                    'bianma' => (new Users())->where('id', $row['user_id'])->value('store_name') ?? '',
                    'name' => $row['mobile'] . $row['name'],
                    'areas' => (new Region())->where(['area_code' => $row['area'], 'level' => 3])->value('name') ?? '',
                    'taocanid' => $taocanid,
                    'taocanname' => $taocanname,
                    'goods_id' => $product['productid'],
                    'title' => $product['title'],
                    'spec' => $par_text,
                    'unit' => $unit ?? '',
                    'guige' => $guige ?? '',
                    'number' => $product['number'],
                    'price' => $product['price'],
                    'total' => floor($product['number'] * $product['price'] * 100) / 100,
                    'created' => $row['created'],
                    'dealer' => $dealer,
                    'address' => ($street['city'] ?? '') . ($street['area'] ?? '') . ($street['street'] ?? '') . ($row['address'] ?? ''),
                    'info' => $row['info'] ?? '',
                    'ordersn' => $row['ordersn']
                ];
            }
        }
        exportDataToExcel($title, $data, date('Y-m-d H:i:s', time()), true, false, $conditions, $merge_cells);
    }

    public function order_excel()
    {
        $ids = input('ids');
        $title = [
            ['field' => 'ordersn', 'width' => 13, 'title' => '订单号'],
            ['field' => 'status_text', 'width' => 13, 'title' => '订单状态'],
            ['field' => 'name', 'width' => 13, 'title' => '用户姓名'],
            ['field' => 'mobile', 'width' => 13, 'title' => '用户电话'],
            ['field' => 'address', 'width' => 13, 'title' => '收货地址'],
            ['field' => 'created', 'width' => 13, 'title' => '创建时间'],
            ['field' => 'product_id', 'width' => 13, 'title' => '产品ID'],
            ['field' => 'product_title', 'width' => 13, 'title' => '产品名称'],
            ['field' => 'product_dealer', 'width' => 13, 'title' => '产品经销商'],
            ['field' => 'product_number', 'width' => 13, 'title' => '产品数量'],
            ['field' => 'product_guige', 'width' => 13, 'title' => '规格'],
            ['field' => 'product_danwei', 'width' => 13, 'title' => '单位'],
            ['field' => 'product_price', 'width' => 13, 'title' => '产品单价'],
            ['field' => 'price_total', 'width' => 13, 'title' => '单品总价'],
            ['field' => 'total', 'width' => 13, 'title' => '合计金额'],
        ];
        //样式  示例：字段 time_difference 大于 0 的行，字体颜色为FF0000
        $conditions =  [];
        //纵向合并单元格  示例：已group_sn字段分组，值相同的合并，include_field（选择字段合并），exclude_field（排除字段合并）,可选择多个
        $merge_cells  = [
            'field' => 'ordersn', //已该字段为分组，值相同的合并
            'include_field' => ['ordersn', 'status_text', 'name', 'mobile', 'address', 'total', 'status_text', 'created'], //合并选择字段
            'exclude_field' => ['product_id', 'product_parame', 'product_title', 'product_dealer', 'product_number', 'product_price', 'price_total', 'product_guige', 'product_danwei'], //合并排除字段
        ];
        $data = [];
        $ids = explode(',', $ids);
        $order = (new Order())->where(['id' => $ids])->select();
        foreach ($order as $row) {
            $products = (new OrderProduct())->where('ordersn', $row['ordersn'])->select();
            $street = getdrees($row['street'], 1);
            $status_text = $row->status_text;
            foreach ($products as $product) {
                $dealer = (new Product())->where('id', $product['productid'])->value('dealer');
                $parame = $product['parame'] ?? '';
                $parame = json_decode($parame, true) ?? [];
                $par_text = '';
                $unit = '';
                $guige = '';
                foreach ($parame as $par) {
                    $par_text = $par_text . '' . $par['name'] . ':' . $par['numbers'] . '  ';
                    if (strpos($par['name'], '单位') !== false) {
                        $unit = $par['numbers'];
                    }
                    if (strpos($par['name'], '规格') !== false) {
                        $guige = $par['numbers'];
                    }
                }
                $data[] = [
                    'ordersn' => $row['ordersn'],
                    'status_text' =>  $status_text,
                    'product_id' => $product['productid'],
                    'product_title' => $product['title'],
                    'product_dealer' => $dealer,
                    'product_number' => $product['number'],
                    'product_price' => $product['price'],
                    'price_total' => floor($product['number'] * $product['price'] * 100) / 100,
                    'name' => $row['name'],
                    'mobile' => $row['mobile'],
                    'address' => ($street['city'] ?? '') . ($street['area'] ?? '') . ($street['street'] ?? '') . ($row['address'] ?? ''),
                    'product_guige' => $guige,
                    'product_danwei' => $unit,
                    //'product_parame' => $par_text,
                    'total' => $row['total'],
                    'created' => $row['created'],
                ];
            }
        }
        exportDataToExcel($title, $data, date('Y-m-d H:i:s', time()), true, false, $conditions, $merge_cells);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Order();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['id|ordersn|name|mobile|address', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['created'])) {
                $start = $post['created']['startime'] ?? (date('Y-m-d') . ' 00:00:00');
                $end = $post['created']['endtime'] ?? (date('Y-m-d') . ' 23:59:59');
                $where[] = ['created', 'between', [$start, $end]];
            }
            if (!empty($post['status'])) {
                if ($post['status'] == 2) {
                    $where[] = ['status', '=', $post['status']];
                    $where[] = ['examine', '=', 1];
                } elseif ($post['status'] == 98) {
                    $where[] = ['status', '=', $post['status']];
                    $where[] = ['examine', '=', 2];
                } else {
                    $where[] = ['status', '=', $post['status']];
                }
            }
            if (!empty($post['issystem'])) {
                $where[] = ['issystem', '=', $post['issystem']];
            }
            if (!empty($post['user'])) {
                $where[] = ['user_id', '=', $post['user']];
            }
            if (!empty($post['payment'])) {
                $where[] = ['payment', '=', $post['payment']];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['riderid'])) {
                $where[] = ['orderid', '=', $post['riderid']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            $ip = $this->request->ip();
            $adminid = $this->request->admin['id'];
            foreach ($list as $lists) {
                $lists['isreads'] = 1;
                $rdsname = 'orders_' . $lists['id'] . $ip . '_' . $adminid;
                $frtimes = Redis::get($rdsname);
                if ($frtimes) {
                    $lists['isreads'] = 2;
                }
                Redis::setex($rdsname, 86400 * 30, $lists['id']);
                $street = getdrees($lists['street'], 1);
                $products = (new OrderProduct())->where('ordersn', $lists['ordersn'])->select();
                foreach ($products as $product) {
                    $product['dealer'] = (new Product())->where('id', $product['productid'])->value('dealer');
                }
                $lists['product'] = $products;
                $lists['province_text'] = $street['province'];
                $lists['city_text'] = $street['city'];
                $lists['area_text'] = $street['area'];
                $lists['street_text'] = $street['street'];
                $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
                $lists['status_text'] = $lists->status_text;
                $lists['payment_text'] = $lists->payment_text;
                $lists['images'] = json_decode($lists['images'], true) ?? [];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'user' => (new Users())->select(),
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function order_edit()
    {
        $id = $this->request->get('id/d', 0);
        $row = (new Order())->where('id', $id)->find();
        if ($row) {
            $row['agent_name'] = (new Agents())->where('id', $row['agentid'])->field('nickname,accounts')->find();
            $products = (new OrderProduct())->where('ordersn', $row['ordersn'])->select();
            foreach ($products as $product) {
                $product['dealer'] = (new Product())->where('id', $product['productid'])->value('dealer');
            }
            $row['product'] = $products;
            $street = getdrees($row['street'], 1);
            $row['province_text'] = $street['province'];
            $row['city_text'] = $street['city'];
            $row['area_text'] = $street['area'];
            $row['street_text'] = $street['street'];
            $row['status_text'] = $row->status_text;
        }
        return view('', [
            'row' => $row
        ]);
    }

    public function order_status()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:2,3,4,5,97,98'
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $order = (new Order())->where('id', $data['id'])->find();
            if (empty($order)) {
                return json(['code' => 1, 'msg' =>  '订单不存在']);
            }
            $orderproduct = (new OrderProduct())->where('ordersn', $order['ordersn'])->select();
            switch ($data['status']) {
                case '2':
                    # code...
                    break;
                case '3':
                    if (empty($data['psnames']) || empty($data['psnumbers'])) {
                        return json(['code' => 1, 'msg' =>  '物流信息不能为空']);
                    }
                    break;
                case '4':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['endtime'] = date('Y-m-d H:i:s');
                    break;
                case '5':
                    if ($order['status'] != 2 && $order['status'] != 3 && $order['status'] != 1) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['caceltime'] = date('Y-m-d H:i:s');
                    if ($order['total'] > 0 && $order['payment'] > 1) {
                        $data['refund'] = 2;
                    }
                    break;
                case '98':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['examine'] = 2;
                    if ($order['status'] <= 2) {
                        $data['status'] = 2;
                    }
                    break;
                case '97':
                    if ($order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $data['examine'] = 3;
                    $data['status'] = 1;
                    break;
                default:
                    return json(['code' => 1, 'msg' =>  '订单类型错误']);
                    break;
            }
            Db::startTrans();
            try {
                (new Order())->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($data['status'] == 5) {
                    foreach ($orderproduct as $oproduct) {
                        (new Product())->SkuEdit($oproduct['productid'], $oproduct['number'], -$oproduct['number'], 2, '取消订单');
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'msg' => '操作失败']);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }
}
